package com.controller;

import com.alibaba.fastjson.JSON;
import com.pojo.User;
import com.servive.UserService;
import com.util.Result;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;

@Controller  //只要你在类上写了这个注解，即标志着他是一个控制器类
@RequestMapping("/user")
public class UserController {

        @Resource
        private UserService userService;

        @RequestMapping("/getUserByid")
        @ResponseBody
        public String getUserByid(int userId) throws Exception {
            User user=  userService.getServiceUserById(userId);
            String struser = JSON.toJSONString(user);
            return struser;
        }

       /* @RequestMapping(value = "/deleUser",produces ={"application/json;charset=UTF-8"})*/
       @RequestMapping(value = "/deleUser")
        @ResponseBody
        public String deleUser(int userId, HttpServletResponse response){
            int i = userService.delServiceUser(userId);
            Result result = new Result();
            if(i>0){
                result.setCord(200);
                result.setMsg("删除成功！");
            }else {
                result.setCord(500);
                result.setMsg("删除失败bbbbbbb！");
            }
            //转Json
            String sjson = JSON.toJSONString(result);
           /* PrintWriter writer = response.getWriter();
            writer.print(sjson);*/
            return sjson;
        }


        @RequestMapping("/toUpFile")
        public String toUpFile(String userName,String userPassword,@RequestParam("pic_file") MultipartFile[] multipartFile) throws IOException {
               //1：文件上传
                String path="E:\\备课笔记\\Kgc备课\\Java全部的课程";
                String file1="";
                String file2="";
              for (int i=0;i<multipartFile.length;i++){
                  MultipartFile multipartFile1= multipartFile[i];

                  String fileName= UUID.randomUUID().toString()+".jpg";
                  File file = new File(path,fileName);
                  //文件上传
                  multipartFile1.transferTo(file);
                  if(i==0){
                      file1=fileName;
                  }else  if(i==1){
                      file2=fileName;
                  }
              }

            //2：持久化数据库
                    User user= new User();
                    user.setUserName(userName);
                    user.setUserPassword(userPassword);
                    user.setPicPath(file1);
                    user.setPhotPath(file2);
                int i = userService.insetServiceUser(user);
                if(i>0){
                    user.getId();
                }


            return "filesuccess";
        }

        //Rset 请求
        /*
        *  @PathVariable：接收的文本字符串
        *  @RequestBody：接收一个Json对象
        *  @ResponseBody: 给前端返回一个Json文本
        * */
        @RequestMapping(value = "/restUrl/{user}",method = RequestMethod.GET)
        public String restUrl(@PathVariable("user") String user){
            User user1 = JSON.parseObject(user, User.class);
            System.out.println("user");

            return "rest";
        }

        /*@RequestMapping("/restUrl/{id}/{name}")
       public String restUrl(@PathVariable("id") Integer id,
                             @PathVariable("name") String name){

           System.out.println("接收:"+id+"=="+name);


           return "rest";
       }*/


        @RequestMapping("/getUser")
        public String getUserByid(Model model) throws Exception {
            //启动ioc容器
            User user=  userService.getServiceUserById(1021);
            if(user == null){
                    throw  new RuntimeException("没有这个数据");
            }
            model.addAttribute("user",user);
            return "userInfo";
        }

       /*  //统一处理
        *//*
        *   注意：
        *       异常方法的参数不能使用 Model传递
        *       方法名称：handlerException
        *   @ExceptionHandler：解决的是局部的异常处理
        * *//*
         @ExceptionHandler(value = {RuntimeException.class})
         public String handlerException(RuntimeException e,HttpServletRequest request){
             request.setAttribute("e",e);
                return "error";
          }
*/

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    //作用：根据请求映射方法
    @RequestMapping("/index")
    public String index(Model model){
        //ModelAndView modelAndView = new ModelAndView();
        model.addAttribute("name","lisi");
        return "login";
    }

    // View --> Controller
    //作用：根据请求映射方法
   /* @RequestMapping("/DoLogin")
    public String Userlogin(HttpServletRequest request, HttpServletResponse response){
        //传统的方式接受参数
        String userName = request.getParameter("userName");
        String UserPassword = request.getParameter("UserPassword");
        return "index";
    }*/
   /* @RequestMapping("/DoLogin")
    public String Userlogin( String userName, String UserPassword
           *//* @RequestParam(value = "userName") String userName,
            @RequestParam(value = "UserPassword") String UserPassword*//*
    ){

        System.out.println("使用映射方式接收参数。");

        return "index";
    }*/

    @RequestMapping("/delUser")
    public String delUser(int id){
        System.out.println("获取参数 id"+id);
        return "index";
    }

    //Controller  ---> View
    @RequestMapping("/DoLogin")
    public String Userlogin(Map map, HttpServletRequest request, HttpSession session, String userName, String UserPassword){

        //第一种传参的方式  Model model
        /*model.addAttribute(userName);
        model.addAttribute("userName",userName);*/
        //第一种传参的方式 使用 servlet  Api
        /*session.setAttribute("userName",userName);
        request.setAttribute("passwod",122);*/
        //第三种： Map
        map.put("userName","ttttt");
        request.setAttribute("passwod",122);
        return "index";
    }
}
